using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Serialization;
using UnityEngine.UI;

public class PlayerController : MonoBehaviour
{
    public static PlayerController player;
    public static Transform playerTransform;
    private Rigidbody _rigidbody;
    private Transform _transform;

    void Awake()
    {
        playerTransform = GetComponent<Transform>();
        player = this;

        _rigidbody = GetComponent<Rigidbody>();
        _transform = GetComponent<Transform>();
    }

    //INPUT
    private Vector3 _iDir = Vector3.zero; //单位向量
    private Vector3 _iRawDir = Vector3.zero; //未经处理的输入向量
    private bool _iLook = false; // 是否站在原地旋转
    void Update()
    {
        _iDir.x = Input.GetAxis("Horizontal");
        _iDir.z = Input.GetAxis("Vertical");
        _iRawDir.x = Input.GetAxisRaw("Horizontal");
        _iRawDir.z = Input.GetAxisRaw("Vertical");
        //限制向量的模长度小于等于1
        if (_iDir.sqrMagnitude > 1f) 
        {
            _iDir = Vector3.Normalize(_iDir); 
        }
    }

    void FixedUpdate()
    {
        Move(_iDir, _iRawDir.sqrMagnitude, _iLook);
    }

    //移动
    private void Move(Vector3 moveDirXz, float rawInputDirSqrMag, bool isLooking)
    {
        if (!isLooking)
        {
            _rigidbody.MovePosition(_transform.position + Time.deltaTime * 7f * moveDirXz);
        }

        // &&左边第一个条件保证玩家松手的时候一定不会转动角色
        // Unity的Input类做了平滑处理
        float rotSpeed = 20f;
        if (isLooking)
        {
            rotSpeed = 5f;
        }

        if (rawInputDirSqrMag > float.Epsilon && moveDirXz.magnitude > float.Epsilon)
        {
            Quaternion rot = Quaternion.LookRotation(moveDirXz, Vector3.up);
            _rigidbody.MoveRotation(Quaternion.Lerp(_rigidbody.rotation, rot, Time.deltaTime * rotSpeed)); //平滑变量硬编码
        }
    }
}

